package com.qd.p2p.web.action.notify.lottery;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Qualifier;

import com.qd.p2p.web.action.notify.TradeNotifyBaseAction;
import com.qd.p2p.web.action.notify.TradeNotifyValueEvent;
import com.qdlc.p2p.biz.processor.event.LotteryCashValueEvent;
import com.qdlc.p2p.biz.service.CollectPayService;
import com.qdlc.p2p.common.constant.NotifyUrl;
import com.qdlc.p2p.common.core.queue.QueueHandlers;
import com.qdlc.p2p.common.util.MailUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.dto.TppTradeLog;

/**
 * 抽奖兑换 - 代收 回调通知
 *
 * @author hongbinglin 2016-01-21
 */
public class NotifyCollectAction extends TradeNotifyBaseAction {

    /** 业务名 */
    private final static String BUSINESS_NAME = "抽奖代收回调";
    /** 业务处理名 */
    private final static String PROCESS_NAME = "代收";

    /** 代收业务处理 */
    @Resource
    @Qualifier("lotteryCollectService")
    private CollectPayService lotteryCollectService;

    /** 代付业务处理 */
    @Resource
    @Qualifier("lotteryPayService")
    private CollectPayService lotteryPayService;

    private static String WEB_URL = SystemConfigHelper.getValue(SystemConfigHelper.Nid.WEB_URL);

    @Override
    @Action(value = NotifyUrl.CASH_LOTTERY_NOTIFY_COLLECT_URL)
    public void doAction() {
        actionHandle();
    }

    @Override
    public String getBusinessName() {
        return BUSINESS_NAME;
    }

    @Override
    public String getProcessName() {
        return PROCESS_NAME;
    }

    @Override
    public void finishHandle(TradeNotifyValueEvent event) {
        // 代收完成业务处理
        lotteryCollectService.tradeFinish(event.getTppTradeLog(), event.getDepositStatus(), event.getDepositAmount());

        try {
            TppTradeLog tppTradeLog = lotteryPayService.createOrder(event.getTppTradeLog());
            // 抽奖现金兑现放入队列中
            LotteryCashValueEvent lotteryCashValueEvent = new LotteryCashValueEvent();
            event.setTppTradeLog(tppTradeLog);
            //将事件放入到队列中
            QueueHandlers.put(lotteryCashValueEvent);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 通知重新发起 抽奖代付
            String reCallUrl = String.format(NotifyUrl.RE_CASH_LOTTERY_PAY_URL, WEB_URL, event.getTppTradeLog().getOrderNo());
            MailUtil.sendMail("抽奖兑现代付-订单生成失败", "代付订单生成失败", reCallUrl);
        }
    }

    @Override
    public void successHandle(TradeNotifyValueEvent event) {
        lotteryCollectService.tradeSuccess(event.getTppTradeLog(), event.getDepositStatus());
    }

    @Override
    public void failHandle(TradeNotifyValueEvent event) {
        lotteryCollectService.tradeFail(event.getTppTradeLog(), event.getDepositStatus());
    }
}
